package com.cheyunkeji.er.utils;

import android.content.Context;
import android.telephony.TelephonyManager;
import android.text.TextUtils;

import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 手机相关工具类
 *
 * @author zhangchaoxian@kankan.com
 */
public class PhoneUtil {

    /**
     * 将手机号码格式为 " " 分割的字符串
     * 012 3456 7890
     *
     * @param phone
     * @return
     */
    public static String format2No(String phone) {
        if (!isMobileNO(phone)) {
            return "";
        }
        StringBuilder builder = new StringBuilder();
        if (TextUtils.isEmpty(phone)) {
            builder.append("");
        } else {
            builder.append(phone.substring(0, 3))
                    .append(" ")
                    .append(phone.substring(3, 7))
                    .append(" ")
                    .append(phone.substring(7, 11));
        }
        return builder.toString();
    }

    /**
     * 还原格式化使用" " 分割的手机号字符串->真实的手机号码
     *
     * @param source
     * @return
     */
    public static String format2RealNo(String source) {
        return source.replace(" ", "");
    }

    /**
     * 校验是否手机号码
     *
     * @param mobiles
     * @return
     */
    public static boolean isMobileNO(String mobiles) {
//        String reg = "^((13[0-9])|(15[^4,\\D])|(18[0,5-9]))\\d{8}$";
        String  reg = "^1[3-9]\\d{9}$";
        Pattern p = Pattern.compile(reg);
        Matcher m = p.matcher(mobiles);
        return m.matches();
    }

    public static String generateDeviceUUID(Context context){
        final TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);

        final String tmDevice, tmSerial, tmPhone, androidId;
        tmDevice = "" + tm.getDeviceId();
        tmSerial = "" + tm.getSimSerialNumber();
        androidId = "" + android.provider.Settings.Secure.getString(context.getContentResolver(), android.provider.Settings.Secure.ANDROID_ID);

        UUID deviceUuid = new UUID(androidId.hashCode(), ((long)tmDevice.hashCode() << 32) | tmSerial.hashCode());
        return deviceUuid.toString();
    }
}
